package com.atguigu.web.admin.custom.converter;

import com.atguigu.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    //这个转换工厂将所有string转为BaseEnum枚举类实例,前端传枚举的code如1，自动转为对应枚举类型
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        //当需要转换为具体的枚举类型T时，spring会调用这方法获取转换器
        return new Converter<String, T>() {//返回匿名转换器实例
            @Override
            public T convert(String source) {
                for (T enumConstant : targetType.getEnumConstants()){
//                    遍历枚举类实例，比较code是否相等
                    if (enumConstant.getCode().equals(Integer.valueOf(source))){
                        //找到匹配的枚举值，返回
                        return enumConstant;
                    }
                }
                throw new IllegalArgumentException("非法的枚举值："+source);
                //没找到匹配的枚举值，抛异常
            }
        };
    }
}
